package com.zerosky.crm.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zerosky.crm.po.Document;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.Train;
import com.zerosky.crm.service.DocumentService;
import com.zerosky.crm.service.TrainService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.MyFileUploadUtils;
import com.zerosky.crm.util.PageInfo;

/**
 * 培训功能的Controller
 * 
 * @author 周正祥
 *
 */
@Controller
public class TrainController extends BaseAction {
	private Logger logger = LoggerFactory.getLogger(TrainController.class); // 日志

	@Resource(name = "trainService")
	private TrainService trainService;

	@Resource(name = "documentService")
	private DocumentService documentService;

	/**
	 * 获取培训文件下载
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/downTrain.do")
	@ResponseBody
	public Map<String, Object> downTrain(HttpServletRequest request, HttpSession session, HttpServletResponse response,
			String url) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			// String
			// url="192.168.2.228:8088/FUNDCRM/saituImage/201711011509500735634.rar";
			MyFileUploadUtils.download(url, response, request);
			json.put("code", "0");
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", "-1");
		}
		return json;

	}

	/**
	 * 获取培训列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/trainList.do")
	@ResponseBody
	public Map<String, Object> TrainList(HttpServletRequest request, HttpSession session, HttpServletResponse response,
			Integer limit, Integer page, String TrainName) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		try {
			param.put("page", page);
			param.put("pageSize", limit);
			if (Strings.isNotEmpty(TrainName)) {
				param.put("trainText", TrainName);
			}
			PageInfo<Train> pageRole = trainService.getTrainList(param);
			json.put("total", pageRole.getPageCount());
			json.put("data", pageRole.getList());
			json.put("code", "0");
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json.put("code", "-1");
		}
		return json;

	}

	/**
	 * 添加培训记录
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertTrain.do")
	@ResponseBody
	public Map<String, Object> insertVisit(Train train, String date1, String date2, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			String StrId = UUID.randomUUID().toString();
			List<Document> list =new ArrayList<Document>();
			if (train.getHotelImgFile() != null) {
				String path = "upload/";
				for (MultipartFile MultipartFile : train.getHotelImgFile()) {
					MyFileUploadUtils.saveFile(request, MultipartFile, path);
					if (request.getAttribute("picture") != null) {
						Document document = new Document();
						document.setRecordId(StrId);
						document.setType("1");
						document.setUrl(path + request.getAttribute("picture"));
						document.setNewName(request.getAttribute("picture").toString());
						document.setName(MultipartFile.getOriginalFilename());
						list.add(document);
					}
				}
			}
			Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
			train.setTrainId(StrId);
			train.setStatus("0");
			train.setStartDate(stringToDateTime(date1));
			train.setEndDate(stringToDateTime(date2));
			train.setCreatePeople(user.getName());// 写入创建用户名称
			train.setCreateDate(new Date());
			if(list.size()>0){
				documentService.addDocumentList(list);
			}
			trainService.saveTrain(train, "新增");
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 修改培训记录
	 * 
	 * @param Train
	 *            对象
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateTrain.do")
	@ResponseBody
	public Map<String, Object> updateVisit(Train train, String date1, String date2, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>();
		try {
			List<Document> list =new ArrayList<Document>();		
			if (train.getHotelImgFile() != null) {
				String path = "upload/";
				for (MultipartFile MultipartFile : train.getHotelImgFile()) {
					MyFileUploadUtils.saveFile(request, MultipartFile, path);
					if (request.getAttribute("picture") != null) {
						Document document = new Document();
						document.setRecordId(train.getTrainId());
						document.setType("1");
						document.setUrl(path + request.getAttribute("picture"));
						document.setNewName(request.getAttribute("picture").toString());
						document.setName(MultipartFile.getOriginalFilename());
						list.add(document);
					}
				}
			}
			train.setStartDate(stringToDateTime(date1));
			train.setEndDate(stringToDateTime(date2));
			if(list.size()>0){
				documentService.deleteDocumentById(train.getTrainId());
				documentService.addDocumentList(list);
			}
			trainService.saveTrain(train, "修改");
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 请求编辑培训信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/editTrain.do")
	@ResponseBody
	public Map<String, Object> editNotice(String trainId, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			Train train = trainService.getTrainById(trainId);
			json.put("train", train);
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 删除记录
	 * 
	 * @param id
	 *            记录编号
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delTrain.do")
	@ResponseBody
	public Map<String, Object> deleteTrainById(String trainId, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			trainService.deleteTrainById(trainId);
			json.put("code", 0);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 跳转培训管理界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toTrain.do")
	public ModelAndView addActivity(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		return new ModelAndView("WEB-INF/jsp/system/trainList");
	}

	/**
	 * 跳转培训列表界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toTrainList.do")
	public ModelAndView toTrainList(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		return new ModelAndView("WEB-INF/jsp/product/trainList");

	}
}
